<template>
  <div>
    <h1>Welcome,Administrator</h1>
    <button @click="$router.push('/page1')">Logout</button>
    <table>
      <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Address</th>
        <th>Actions</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="user in users"
          :key="user.id">
        <td>{{ user.name }}</td>
        <td>{{user.age}}</td>
        <td>{{user.address}}</td>
      <td>
        <button @click="editUser(user)">Edit</button>
        <button @click="deleteUser(user.id)">Delete</button>
      </td>
      </tr>
      </tbody>
    </table>
    <button @click="addUser">AddUser</button>
    <div v-if="showModel">
      <div class="modal">
        <h2>{{modalTitle}}</h2>
        <form @submit.prevent="saveUser">
          <input type="text" v-model="selectedUser.name" placeholder="Name">
          <input type="number" v-model="selectedUser.age" placeholder="Age">
          <input type="text" v-model="selectedUser.address" placeholder="Address">
          <button type="submit">Save</button>
          <button type="button" @click="closeModal">Cancel</button>
        </form>
      </div>
    </div>
  </div>
  </template>

<script>
export default {
  data() {
    return {
      users: [
        {id: 1, name: 'John', age: 25, address: '123 Street'},
        {id: 2, name: 'Jane', age: 30, address: '456 Avenue'},
        {id: 3, name: 'Bob', age: 35, address: '789 Road'},
      ],
      showModel: false,
      modalTitle: '',
      selectedUser: {}
    }
  },
  methods: {
    addUser() {
      this.modalTitle = 'Add User';
      this.selectedUser = {};
      this.showModel = true;
    },
    editUser(user) {
      this.modalTitle = 'Edit User';
      this.selectedUser = {...user};
      this.showModel = true;
    },
    saveUser() {
      if (this.modalTitle === 'Add User') {
        this.users.push({
          id: this.users.length + 1,
          name: this.selectedUser.name,
          age: this.selectedUser.age,
          address: this.selectedUser.address
        });
      } else {
        const index = this.users.findIndex(u => u.id === this.selectedUser.id);
        this.users[index] = this.selectedUser;
      }
      this.closeModel();
    },
    deleteUser(id) {
      if (confirm('Are you sure you want to delete this user?')) {
        this.users = this.users.filter(u => u.id === id);
      }
    },
    closeModal() {
      this.showModel = false;
    }
  }
}
</script>

<style scoped>
.modal{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 20px;
  border: 1px solid black;
  z-index: 1;
}
</style>

